// 首页
import * as types from '@/store/mutation-types'
// import { isArray, isEmpty, hasIn } from 'lodash'
import api from '@/tools/api.js'
import { SUCCESS_STATUS } from '@/config/status'
import promise from '@/tools/promise'

const state = {
  allList: [],
  pageData: {
    total: 1,
    per_page: 15,
    current_page: 1,
    last_page: 1
  },
  noPageRoleList: [],
  detail: {}
}

// actions
const actions = {
  // 获取所有角色分页列表
  async getAll ({ commit }, payload) {
    let config = { loading: true, loadingText: '正在获取角色列表' }
    let getRes = await api('serverauth/role/Role/list', payload, config)
    SUCCESS_STATUS === getRes.status && commit(types.GET_ALL_ROLES, getRes.res)
  },
  // 获取所有角色 不分页
  async getNoPageRole ({ commit }) {
    let getNoPageRes = await api('serverauth/role/Role/all')
    SUCCESS_STATUS === getNoPageRes.status && commit(types.GET_NO_PAGE_ROLES, getNoPageRes.res)
  },
  // 给某用户添加某个角色
  async addUserOneRole ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在为用户添加该角色'}
    let addRoleRes = await api('serverauth/role/Role/giveRoles', payload, config)
    return promise(addRoleRes)
  },
  // 移除某用户某个角色
  async removeUserOneRole ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在移除用户该角色'}
    let removeRoleRes = await api('serverauth/role/Role/removeUserRole', payload, config)
    return promise(removeRoleRes)
  },
  // 添加一个角色
  async addRole ({ commit }, payload) {
    let config = {loading: true, loadingText: '正在添加角色...'}
    let addRes = await api('serverauth/role/Role/add', payload, config)
    return promise(addRes)
  },
  // 禁用某个角色
  async stopRole ({ commit }, payload) {
    let stopRes = await api('serverauth/role/Role/stop', payload)
    return promise(stopRes)
  },
  // 启用某个角色
  async startRole ({ commit }, payload) {
    let startRes = await api('serverauth/role/Role/start', payload)
    return promise(startRes)
  },
  // 获取某个角色的详情
  async roleInfo ({ commit }, payload) {
    let infoRes = await api('serverauth/role/Role/getRoleInfo', payload)
    SUCCESS_STATUS === infoRes.status && commit(types.GET_ROLE_DETAIL, infoRes.res)
  },
  // 编辑某个角色
  async editRole ({ commit }, payload) {
    let editRes = await api('serverauth/role/Role/edit', payload)
    return promise(editRes)
  }
}

// mutations
const mutations = {
  [types.GET_ALL_ROLES] (state, payload) {
    state.allList = payload.data
    state.pageData.total = Number(payload.total)
    state.pageData.per_page = Number(payload.per_page)
    state.pageData.current_page = Number(payload.current_page)
    state.pageData.last_page = Number(payload.last_page)
  },
  [types.GET_NO_PAGE_ROLES] (state, payload) {
    state.noPageRoleList = payload
  },
  [types.GET_ROLE_DETAIL] (state, payload) {
    state.detail = payload
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
